package com.lagou.edu.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lagou.edu.common.status.ResultStatus;
import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.entity.Token;
import com.lagou.edu.entity.User;
import com.lagou.edu.fegin.IAuthCodeServiceClient;
import com.lagou.edu.service.IUserService;
import com.lagou.edu.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * @author 赵虎
 * @date 2021/2/22 10:55 上午
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Autowired
    private IAuthCodeServiceClient iAuthCodeServiceClient;

    @Override
    public ResultVO register(String email, String password, String code) {
        if (isRegistered(email)) {
            ResultVO.fail(ResultStatus.ERROR_SYSTEM, "该邮箱已注册！");
        }

        ResultVO resultVO = iAuthCodeServiceClient.validateAuthCode(email, code);
        if(resultVO.getStatus().equals(ResultStatus.SUCCESS.getCode())){
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            user.setCreatetime(new Date());
            userDao.save(user);

            return resultVO.ok(generateToken(email));
        }
        return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "登录失败");
    }

    @Override
    public boolean isRegistered(String email) {
        User user = userDao.findFirstByEmail(email);
        return !Objects.isNull(user);
    }

    @Override
    public ResultVO login(String email, String password) {
        User user = userDao.findFirstByEmail(email);
        if (Objects.isNull(user)) {
            return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "查无此人");
        }
        if (user.getPassword().equals(password)) {
            return ResultVO.ok(generateToken(email));
        }
        return ResultVO.fail(ResultStatus.ERROR_SYSTEM, "登录失败");
    }

    @Override
    public String getEmailByToken(String tokenText) {
        Token token = tokenDao.findFirstByToken(tokenText);
        return token == null ? "" : token.getEmail();
    }

    private Token generateToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        token.setToken(IdUtil.simpleUUID());
        return tokenDao.save(token);
    }
}
